<?php
require_once 'config.php';

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

// 获取输入数据
$input = file_get_contents('php://input');
$params = [];

if (!empty($input)) {
    $params = json_decode($input, true);
}

if (empty($params)) {
    $params = $_REQUEST;
}

// 清理参数，确保数据类型正确
foreach ($params as $key => $value) {
    if ($value === '') {
        unset($params[$key]);
    } elseif (in_array($key, ['points', 'elapsed_time', 'blue_score', 'red_score'])) {
        $params[$key] = (int)$value;
    } elseif ($key === 'is_running') {
        $params[$key] = (bool)$value;
    } elseif ($key === 'start_time') {
        $params[$key] = $value !== null ? (int)$value : null;
    }
}

$action = $params['action'] ?? '';
$response = ['success' => false, 'message' => '未知操作', 'data' => null];

try {
    switch ($action) {
        case 'get_data':
            $timerData = getTimerData();
            $currentTime = $timerData['elapsed_time'];
            
            if ($timerData['is_running'] && $timerData['start_time']) {
                $currentTime += (time() - $timerData['start_time']);
            }
            
            $response = [
                'success' => true,
                'message' => '获取数据成功',
                'data' => [
                    'elapsed_time' => (int)$currentTime,
                    'is_running' => (bool)$timerData['is_running'],
                    'blue_score' => (int)$timerData['blue_score'],
                    'red_score' => (int)$timerData['red_score'],
                    'timestamp' => time()
                ]
            ];
            break;
            
        case 'add_blue':
            $points = isset($params['points']) ? (int)$params['points'] : 1;
            $timerData = getTimerData();
            $newScore = (int)$timerData['blue_score'] + $points;
            
            updateTimerData(['blue_score' => $newScore]);
            
            $response = [
                'success' => true,
                'message' => '蓝方分数增加成功',
                'data' => [
                    'blue_score' => $newScore,
                    'red_score' => (int)$timerData['red_score'],
                    'timestamp' => time()
                ]
            ];
            break;
            
        case 'add_red':
            $points = isset($params['points']) ? (int)$params['points'] : 1;
            $timerData = getTimerData();
            $newScore = (int)$timerData['red_score'] + $points;
            
            updateTimerData(['red_score' => $newScore]);
            
            $response = [
                'success' => true,
                'message' => '红方分数增加成功',
                'data' => [
                    'blue_score' => (int)$timerData['blue_score'],
                    'red_score' => $newScore,
                    'timestamp' => time()
                ]
            ];
            break;
            
        case 'start_timer':
            $timerData = getTimerData();
            
            if (!$timerData['is_running']) {
                updateTimerData([
                    'start_time' => time(),
                    'is_running' => true
                ]);
                
                $response = [
                    'success' => true,
                    'message' => '计时器已启动',
                    'data' => [
                        'is_running' => true,
                        'timestamp' => time()
                    ]
                ];
            } else {
                $response = [
                    'success' => false,
                    'message' => '计时器已经在运行中',
                    'data' => [
                        'is_running' => true
                    ]
                ];
            }
            break;
            
        case 'stop_timer':
            $timerData = getTimerData();
            
            if ($timerData['is_running']) {
                $elapsed = (int)$timerData['elapsed_time'] + (time() - (int)$timerData['start_time']);
                updateTimerData([
                    'is_running' => false,
                    'elapsed_time' => $elapsed,
                    'start_time' => null
                ]);
                
                $response = [
                    'success' => true,
                    'message' => '计时器已停止',
                    'data' => [
                        'is_running' => false,
                        'elapsed_time' => $elapsed,
                        'timestamp' => time()
                    ]
                ];
            } else {
                $response = [
                    'success' => false,
                    'message' => '计时器已经停止',
                    'data' => [
                        'is_running' => false
                    ]
                ];
            }
            break;
            
        case 'reset_all':
            try {
                $pdo = getDBConnection();
                
                // 使用事务确保数据一致性
                $pdo->beginTransaction();
                
                // 直接执行SQL重置
                $stmt = $pdo->prepare("
                    UPDATE timer_data 
                    SET 
                        start_time = NULL,
                        is_running = 0,
                        elapsed_time = 0,
                        blue_score = 0,
                        red_score = 0,
                        last_updated = NOW()
                    WHERE id = 1
                ");
                
                $success = $stmt->execute();
                
                if ($success && $stmt->rowCount() > 0) {
                    $pdo->commit();
                    
                    $response = [
                        'success' => true,
                        'message' => '重置成功',
                        'data' => [
                            'elapsed_time' => 0,
                            'is_running' => false,
                            'blue_score' => 0,
                            'red_score' => 0,
                            'timestamp' => time()
                        ]
                    ];
                } else {
                    $pdo->rollBack();
                    throw new Exception('数据库更新失败');
                }
                
            } catch (Exception $e) {
                $pdo->rollBack();
                throw new Exception('重置失败: ' . $e->getMessage());
            }
            break;
            
        default:
            $response = ['success' => false, 'message' => '无效的操作: ' . $action, 'data' => null];
            break;
    }
} catch (Exception $e) {
    $response = ['success' => false, 'message' => '服务器错误: ' . $e->getMessage(), 'data' => null];
    error_log('API Error: ' . $e->getMessage());
}

echo json_encode($response);
?>